from django.shortcuts import render,HttpResponse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django_redis import get_redis_connection


# Create your views here.
def send_sms(request):
    """ 发送短信 """
    tpl = request.GET.get('tql')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)
    res = send_sms_single('13794290553', template_id, [code, 1])
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )
    password = forms.CharField(label="密码", widget=forms.PasswordInput())
    cofirm_password = forms.CharField(label="重置密码", widget=forms.PasswordInput())
    code = forms.CharField(label="验证码")

    class Meta:
        model = models.UserInfo
        fields = ["username", "email", "password", "cofirm_password", "mobile_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)

    # def clean_mobile(self):
    #     # 当前编辑的ID
    #     txt_mobile = self.cleaned_data["mobile_phone"]
    #     exists = models.UserInfo.objects.exclude(id=self.instance.pk).filter(mobile_phone=txt_mobile).exists()
    #     if exists:
    #         # 验证不通过
    #         raise ValidationError("手机号已存在")
    #     # 验证通过，用户输入的值返回
    #     return txt_mobile


def register(request):
    form = RegisterModelForm()
    return render(request,'app01/register.html',{'form':form})


def index(request):
    # 去连接池中获取一个连接
    conn = get_redis_connection("0")
    conn.set('nickname', "武沛齐", ex=10)
    value = conn.get('nickname')
    print(value)
    return HttpResponse("OK")
